<?php
/**
 * 设备绑定.
 * User: dxk
 * Date: 2021-01-04
 */
namespace App\Service\AppPush;

use App\Library\Service\AliCloud\AppPush;

class DeviceBindService
{
    private $alicloud_app_key;

    public function __construct($api_key)
    {
        $msg_push = config('sys.aliyun.msg_push');
        if (!isset($msg_push[$api_key])) {
            $this->alicloud_app_key = '';
        } else {
            $this->alicloud_app_key = $msg_push[$api_key]['appKey'];
        }
    }

    /**
     * 设备登录
     * @param $user_id
     * @param $device_id
     * @return array
     */
    public function appLogin($user_id, $device_id): array
    {
        $user_id = (int)$user_id;
        $device_id = trim($device_id);
        if (empty($device_id) || $user_id <= 0) {
            return alert_info(1, '参数错误');
        }
        //---------------别名绑定-------------
        $alias_names = [
            AppPushService::getInstance()->getUserAlias($this->alicloud_app_key, $user_id),
        ];
        sort($alias_names);
        //获取此设备的绑定
        $res = (new AppPush($this->alicloud_app_key))->QueryAliases(['DeviceId' => $device_id]);
        $has_bind_alias = $res['data']['AliasInfos']['AliasInfo'] ?: [];
        $has_bind_alias = array_column($has_bind_alias, 'AliasName');
        sort($has_bind_alias);
        if (md5(serialize($alias_names)) != md5(serialize($has_bind_alias))) {
            if ($has_bind_alias) {
                (new AppPush($this->alicloud_app_key))->UnbindAlias(['DeviceId' => $device_id, 'UnbindAll' => true]);
            }
            (new AppPush($this->alicloud_app_key))->BindAlias(['DeviceId' => $device_id, 'AliasName' => implode(',', $alias_names)]);
        }
        return ['alias' => $alias_names];
    }

    /**
     * 设备登出
     * @param $user_id
     * @param $device_id
     * @return array
     */
    public function appLoginOut($user_id, $device_id): array
    {
        $user_id = (int)$user_id;
        $device_id = trim($device_id);
        if (empty($device_id) || $user_id <= 0) {
            return alert_info(1, '参数错误');
        }
        //---------------别名解除绑定-------------
        $alias_names = [
            AppPushService::getInstance()->getUserAlias($this->alicloud_app_key, $user_id),
        ];
        (new AppPush($this->alicloud_app_key))->UnbindAlias(['DeviceId' => $device_id, 'AliasName' => implode(',', $alias_names)]);
        return ['alias' => $alias_names];
    }
}
